package MockDb;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import DbObjects.Person;

public class StaticMockDb implements IMockDb<Person>
{
	private List<Person> _personList;
	private IMockDbInitializer<Person> _initializer;
	
	public StaticMockDb()
	{
		_personList = Collections.synchronizedList(new ArrayList<Person>());
		this._initializer = null;
	}
	
	public StaticMockDb(IMockDbInitializer<Person> initializer)
	{
		this._initializer = initializer;
	}
	
	@Override
	public synchronized boolean Add(Person itemToAdd) throws Exception
	{
		if(itemToAdd == null)
			throw new Exception();
		
		return this._personList.add(itemToAdd);
	}

	@Override
	public synchronized boolean Remove(Person itemToRemove) throws Exception
	{
		if(itemToRemove == null)
			throw new Exception();
		
		return this._personList.remove(itemToRemove);
	}

	@Override
	public synchronized Person Get(int id) 
	{
		for(Person person : this._personList)
			if(person.getPersonId() == id)
				return person;
		
		return null;
	}

	@Override
	public synchronized Iterable<Person> GetAll() 
	{
		return (Iterable<Person>)this._personList;
	}

	@Override
	public synchronized boolean Remove(int id) throws Exception 
	{
		Person person = Get(id);
		
		if(person == null)
			return false;
		
		return this._personList.remove(person);
	}

	@Override
	public synchronized boolean Update(Person itemToUpdate) throws Exception 
	{
		if(itemToUpdate == null)
			throw new Exception();
		
		Person originalPerson = Get(itemToUpdate.getPersonId());
		
		if(originalPerson == null)
			return false;
		
		int index = this._personList.indexOf(originalPerson);
		if(index >= 0)
			return (this._personList.set(index, itemToUpdate) != null);
		
		return false;
	}
	
	@Override
	public synchronized int Count()
	{
		if(this._personList.isEmpty())
			return 0;
		
		return this._personList.size();
	}
	
	@Override
	public synchronized void Initialize()
	{
		this._personList = Collections.synchronizedList(new ArrayList<Person>());
		
		if(this._initializer != null)
		{
			for(Person p : this._initializer.InitializeDb())
			{
				this._personList.add(p);
			}
		}
	}
}
